<!-- 首件检验合格率报表 -->
<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="搜索"> </el-tab-pane>
      <avue-form ref="form" :option="option" v-model="form">
        <template slot="btn">
          <el-button type="primary" size="small" class="el-icon-search" @click="handleSubmit">搜索</el-button>
          <el-button size="small" class="el-icon-delete" @click="handleCancel">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="chart-tab tab-font">
      <el-tab-pane label="明细"> </el-tab-pane>
      <div class="chart-header">
        <el-dropdown @command="handleExport">
          <el-button type="warning" size="small">导出<i class="el-icon-download"></i> </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="pdf">导出pdf</el-dropdown-item>
            <el-dropdown-item command="excel">导出excel</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-row :gutter="20" id="element-to-print">
        <el-col :span="24">
          <chart-view class="chart-content" :chart-option="chartOption" :auto-resize="true" width="100%" />
          <avue-crud
            @on-load="onLoad"
            :option="tableOption"
            :table-loading="loading"
            :data="data"
            v-model="model"
            :page="tablePage"
            :before-open="beforeOpen"
            @current-change="currentChange"
            @size-change="sizeChange"
            ref="crud"
          >
          </avue-crud>
        </el-col>
      </el-row>
    </el-tabs>
    <export-comp
      ref="exportExcel"
      page-api-url="mes-product/qms-inspection-document-report/pass-rate/page"
      file-name="制程检验合格率报表"
      :option="tableOption"
      :page="tablePage"
      :query="search"
    ></export-comp>
    <export-pdf
      ref="exportPdf"
      url="/api/mes-product/qms-inspection-document-report/pass-rate/page"
      name="制程检验合格率报表"
      :option="tableOption"
      :chartOption="chartOption"
      :page="tablePage"
      :query="search"
      :data="data"
    ></export-pdf>
  </basic-container>
</template>

<script>
import ChartView from '@/components/chart/index.vue';
import moment from 'moment';
import { mapGetters } from 'vuex';
import { tableOption, option } from '@/views/report/processInspectionReport.js';
import { getQualityList } from '@/api/report/report';
import ExportComp from '@/components/export-comp';
import exportPdf from '@/components/export-pdf/index.vue';
export default {
  name: 'processInspectionReport',
  components: {
    ChartView,
    exportPdf,
    ExportComp
  },
  data() {
    return {
      visible: false,
      search: {},
      model: {},
      form: {},
      loading: false,
      data: [],
      tableOption,
      tablePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option,
      chartOption: {
        title: {
          text: '制程检验批合格率统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
          // formatter: '{a0}: {c0}<br />{a1}: {c1}%'
        },
        legend: {
          top: '10%',
          tooltip: {
            show: true
            // formatter: function ({ name }) {
            //   return name === '直通率' ? 'PPM为所有生产该产品的工单直通率的平均值' : '产量';
            // }
          }
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            rotate: 30
          },
          //   boundaryGap: false,
          data: [],
          name: '',
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: [
          {
            type: 'value',
            // min: 0,
            // max: 120,
            // interval: 20,
            axisLabel: {
              formatter: '{value}'
            },
            nameTextStyle: {
              // fontWeight: 'bold',
              // fontSize: 16
              // padding: [0, 60, 20, 0]
            },
            name: ''
            // nameLocation: 'start'
          },
          {
            type: 'value',
            min: 0,
            max: 100,
            interval: 20,
            axisLabel: {
              formatter: '{value}%'
            },
            nameTextStyle: {
              // fontWeight: 'bold',
              // fontSize: 16
              // padding: [0, 60, 20, 0]
            },
            name: ''
            // nameLocation: 'start'
          }
        ],
        series: [
          {
            name: '总检批次',
            type: 'bar',
            data: [],
            color: ['#02a7f0']
          },
          {
            name: '合格批次',
            type: 'bar',
            data: [],
            color: ['#ee822f']
          },
          {
            name: '目标值',
            type: 'line',
            data: [],
            color: ['#f6d054'],
            yAxisIndex: 1
          },
          {
            name: 'LAR值',
            type: 'line',
            data: [],
            color: ['#75bd42'],
            yAxisIndex: 1
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  mounted() {},
  methods: {
    handleExport(val) {
      if (val === 'excel') {
        this.$refs.exportExcel.visible = true;
      } else {
        this.$refs.exportPdf.openDialog();
      }
    },
    beforeOpen(done, type) {
      if (['view'].includes(type)) {
        this.$router.push({
          path: `/quality/refactor/processInspectionRecord`,
          query: {
            lineId: this.model.lineId,
            examineDate: this.model.date
          }
        });
      }
    },
    close() {
      this.$refs.exportPdf.visible = false;
    },
    onLoad() {
      const params = {
        current: this.tablePage.currentPage,
        size: this.tablePage.pageSize,
        documentType: 'IPQC'
      };
      if (this.form.date.length > 0) {
        params.startTime = this.form.date[0];
        params.endTime = this.form.date[1];
      }
      if (this.form.lineName) {
        params.lineId = this.form.lineName;
      }
      this.search = params;
      this.loading = true;
      getQualityList(params)
        .then((res) => {
          let data = res.data.data;
          this.data = data.records || [];
          this.tablePage.total = data.total;
          this.setChartOption(data);
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad();
    },
    setChartOption(data) {
      let xAxisList = [];
      let examineTotalTimesList = [];
      let examineOkTimesList = [];
      let targetValueList = [];
      let passRateList = [];
      this._forEach(data.records, (item) => {
        xAxisList.push(`${item.date}+${item.lineName}`);
        examineTotalTimesList.push(item.examineTotalTimes && item.examineTotalTimes != null ? item.examineTotalTimes : 0);
        examineOkTimesList.push(item.examineOkTimes && item.examineOkTimes != null ? item.examineOkTimes : 0);
        targetValueList.push(item.targetValue && item.targetValue != null ? item.targetValue : 0);
        passRateList.push(item.passRate && item.passRate != null ? item.passRate : 0);
      });
      const series = [
        {
          name: '总检批次',
          type: 'bar',
          data: examineTotalTimesList,
          color: ['#4874cb']
        },
        {
          name: '合格批次',
          type: 'bar',
          data: examineOkTimesList,
          color: ['#ee822f']
        },
        {
          name: '目标值',
          type: 'line',
          data: targetValueList,
          color: ['#f6d054'],
          yAxisIndex: 1,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' %';
            }
          }
        },
        {
          name: 'LAR值',
          type: 'line',
          data: passRateList,
          color: ['#75bd42'],
          yAxisIndex: 1,
          tooltip: {
            valueFormatter: function (value) {
              return value + ' %';
            }
          }
        }
      ];
      const xAxis = {
        type: 'category',
        data: xAxisList,
        axisLabel: {
          formatter: function (value) {
            let partnerNo = value.split('+')[0] !== 'null' ? value.split('+')[0] : '';
            let date = value.split('+')[1] !== 'null' ? value.split('+')[1] : '';
            return `${date}\n${partnerNo}`;
          }
        },
        axisTick: {
          alignWithLabel: false
        }
        // axisLabel: {
        //   rotate: 30
        // }
      };
      this.$set(this.chartOption, 'xAxis', xAxis);
      this.$set(this.chartOption, 'series', series);
    },
    handleSubmit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.onLoad();
          done();
        }
      });
    },
    handleCancel() {
      this.$nextTick(() => {
        this.data = [];
        this.search = {};
        this.tablePage.total = 0;
        this.tablePage.currentPage = 1;
        this.tablePage.pageSize = 15;
        // this.params.startDate = '';
        // this.params.endDate = '';
      });
      const series = this.chartOption.series.map((item) => ({ ...item, data: [] }));
      this.$refs.form.resetForm();
      this.$set(this.chartOption, 'series', series);
    }
  }
};
</script>

<style scoped lang="scss">
.chart-tab {
  margin-top: 24px;
  height: calc(100vh - 350px);
  overflow-y: scroll;
}
.chart-header {
  display: flex;
  justify-content: start;
  align-items: center;
  margin-bottom: 10px;
}
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
</style>
